package com.handong.handserialprogram.module.others;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.text.InputFilter;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.handong.handserialprogram.R;
import com.handong.handserialprogram.module.base.BackStackFragment;
import com.handong.handserialprogram.module.tasklist.TaskListActivity;
import com.handong.handserialprogram.utils.AppUtil;
import com.handong.handserialprogram.utils.SPUtil;
import com.handong.handserialprogram.utils.ViewUtil;
import com.handong.handserialprogram.widget.IPInputView;

/**
 */
public class SetIPAddressFragment extends BackStackFragment {

    private static final String FIRST_BOOT = "first_boot";

    private boolean mIsFirstBoot = true;

    private IPInputView mIPInputView,mfootringIp;
    private EditText mMissionPort, mUploadPort,mChatPort,mFilePort,mVideoPort,mFootringPort;


    public SetIPAddressFragment() {
    }

    public static SetIPAddressFragment newInstance(boolean isFirstBoot) {
        SetIPAddressFragment fragment = new SetIPAddressFragment();
        Bundle args = new Bundle();
        args.putBoolean(FIRST_BOOT, isFirstBoot);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mIsFirstBoot = getArguments().getBoolean(FIRST_BOOT);
        }
    }

    @Override
    protected int getContentViewID() {
        return R.layout.fragment_set_ip;
    }

    @Override
    protected void initViewByID(View view) {
        mIPInputView = (IPInputView) view.findViewById(R.id.ipInputView);
        mfootringIp= (IPInputView) view.findViewById(R.id.footringIpInputView);
        mMissionPort = (EditText) view.findViewById(R.id.portViewMission);
        mUploadPort = (EditText) view.findViewById(R.id.portViewUpload);
        mChatPort = (EditText) view.findViewById(R.id.portChat);
        mFilePort=(EditText) view.findViewById(R.id.portFile);
        mVideoPort=(EditText) view.findViewById(R.id.portVideo);
        mFootringPort=(EditText) view.findViewById(R.id.portFootring);
    }

    @Override
    protected void initViewData() {
        initHeaderLayout(R.string.nav_config_server, getContext().getResources().getString(R.string.option_text_commit));

        InputFilter[] lengthFilter = new InputFilter[]{new InputFilter.LengthFilter(5)};
        mUploadPort.setFilters(lengthFilter);
        mMissionPort.setFilters(lengthFilter);
        mFootringPort.setFilters(lengthFilter);
        mChatPort.setFilters(lengthFilter);
        mFilePort.setFilters(lengthFilter);
        mVideoPort.setFilters(lengthFilter);
        String ip = SPUtil.getStringValue(SPUtil.SERVER_IP);
        if (!TextUtils.isEmpty(ip)) {
            mIPInputView.setContentText(ip);
        }
        String footringip = SPUtil.getStringValue(SPUtil.FOOTRING_SERVER_IP);
        if (!TextUtils.isEmpty(footringip)) {
            mfootringIp.setContentText(footringip);
        }
        int missionPort = SPUtil.getIntValue(SPUtil.MISSION_PORT);
        if (missionPort != 0) {
            mMissionPort.setText(String.valueOf(missionPort));
        }
        int uploadPort = SPUtil.getIntValue(SPUtil.UPLOAD_PORT);
        if (uploadPort != 0) {
            mUploadPort.setText(String.valueOf(uploadPort));
        }
        int chatPort = SPUtil.getIntValue(SPUtil.CHAT_PORT);
        if (chatPort != 0) {
            mChatPort.setText(String.valueOf(chatPort));
        }
        int filePort = SPUtil.getIntValue(SPUtil.FILE_PORT);
        if (filePort != 0) {
            mFilePort.setText(String.valueOf(filePort));
        }
        int videoPort = SPUtil.getIntValue(SPUtil.VIDEO_PORT);
        if (videoPort != 0) {
            mVideoPort.setText(String.valueOf(videoPort));
        }
        int footPort = SPUtil.getIntValue(SPUtil.FOOT_PORT);
        if (footPort != 0) {
            mFootringPort.setText(String.valueOf(footPort));
        }
        ViewUtil.changeEditTextStatus(mMissionPort);
        ViewUtil.changeEditTextStatus(mUploadPort);
        ViewUtil.changeEditTextStatus(mChatPort);
        ViewUtil.changeEditTextStatus(mFilePort);
        ViewUtil.changeEditTextStatus(mVideoPort);
        ViewUtil.changeEditTextStatus(mFootringPort);

    }

    @Override
    public void onClick(View v) {
        if (dispatchDoubleClick()){
            return;
        }
        switch (v.getId()) {
            case R.id.headerOptionLayout:
                if (saveIPAndPort()) {
                    if (mIsFirstBoot) {
                        Intent intent = new Intent(getActivity(), TaskListActivity.class);
                        startActivity(intent);
                        SPUtil.putBooleanValue(FIRST_BOOT, true);
                    }
                    removeFrag(this);
                }
                break;
            case R.id.headerBackLayout:
                getActivity().onBackPressed();
                break;
        }
    }

    private boolean saveIPAndPort() {
        String ip = mIPInputView.getContentIP();
        if (TextUtils.isEmpty(ip)) {
            AppUtil.showShortToast(getContext(), "IP不能为空");
            return false;
        }
        String footip = mfootringIp.getContentIP();
        if (TextUtils.isEmpty(footip)) {
            AppUtil.showShortToast(getContext(), "脚环服务端IP不能为空");
            return false;
        }
        if (!AppUtil.isCorrectInternetAddressByMatch(ip)) {
            AppUtil.showShortToast(getContext(), "IP格式不正确");
            return false;
        }
        String missionPort = mMissionPort.getText().toString().trim();
        if (TextUtils.isEmpty(missionPort)) {
            AppUtil.showShortToast(getContext(), "获取任务端口不能为空");
            return false;
        }
        String uploadPort = mUploadPort.getText().toString().trim();
        if (TextUtils.isEmpty(uploadPort)) {
            AppUtil.showShortToast(getContext(), "上传信息端口不能为空");
            return false;
        }
        String chatPort = mChatPort.getText().toString().trim();
        if (TextUtils.isEmpty(chatPort)) {
            AppUtil.showShortToast(getContext(), "聊天服务端口不能为空");
            return false;
        }
        String filePort = mFilePort.getText().toString().trim();
        if (TextUtils.isEmpty(filePort)) {
            AppUtil.showShortToast(getContext(), "文件存储端口不能为空");
            return false;
        }
        String videoPort = mVideoPort.getText().toString().trim();
        if (TextUtils.isEmpty(videoPort)) {
            AppUtil.showShortToast(getContext(), "视频推流端口不能为空");
            return false;
        }

        String footPort = mFootringPort.getText().toString().trim();
        if (TextUtils.isEmpty(footPort)) {
            AppUtil.showShortToast(getContext(), "脚环上传端口不能为空");
            return false;
        }
        int missionPortInt = Integer.parseInt(missionPort);

        if (missionPortInt < 0 || missionPortInt > 65535) {
            AppUtil.showShortToast(getContext(), "获取任务端口格式不正确");
            return false;
        }
        int uploadPortInt = Integer.parseInt(uploadPort);
        if (uploadPortInt < 0 || uploadPortInt > 65535) {
            AppUtil.showShortToast(getContext(), "上传信息端口格式不正确");
            return false;
        }
        int chatPortInt = Integer.parseInt(chatPort);
        if (chatPortInt < 0 || chatPortInt > 65535) {
            AppUtil.showShortToast(getContext(), "聊天服务端口格式不正确");
            return false;
        }
        int filePortInt = Integer.parseInt(filePort);
        if (filePortInt < 0 || filePortInt > 65535) {
            AppUtil.showShortToast(getContext(), "文件存储端口格式不正确");
            return false;
        }
        int videoPortInt = Integer.parseInt(videoPort);
        if (videoPortInt < 0 || videoPortInt > 65535) {
            AppUtil.showShortToast(getContext(), "视频推流端口格式不正确");
            return false;
        }
        int footPortInt = Integer.parseInt(footPort);
        if (footPortInt < 0 || footPortInt > 65535) {
            AppUtil.showShortToast(getContext(), "脚环上传端口格式不正确");
            return false;
        }
        if (!TextUtils.isEmpty(SPUtil.getStringValue(SPUtil.LOGIN_CODE))) {
            if (!footip.equals(SPUtil.getStringValue(SPUtil.FOOTRING_SERVER_IP))||!ip.equals(SPUtil.getStringValue(SPUtil.SERVER_IP)) || missionPortInt != SPUtil.getIntValue(SPUtil.MISSION_PORT)
                    || uploadPortInt != SPUtil.getIntValue(SPUtil.UPLOAD_PORT)|| chatPortInt != SPUtil.getIntValue(SPUtil.CHAT_PORT)|| filePortInt != SPUtil.getIntValue(SPUtil.FILE_PORT)|| videoPortInt != SPUtil.getIntValue(SPUtil.VIDEO_PORT)|| footPortInt != SPUtil.getIntValue(SPUtil.FOOT_PORT)) {
                showTipsDialog(ip, missionPortInt, uploadPortInt,chatPortInt,filePortInt,videoPortInt,footPortInt,footip);
                return false;
            }
        }
        savePreference(ip, missionPortInt, uploadPortInt,chatPortInt,filePortInt,videoPortInt,footPortInt,footip);
        return true;
    }

    private void showTipsDialog(final String ip, final int missionPortInt, final int uploadPortInt,final int chatPortInt,final int filePortInt,final int videoPortInt,final int footPortInt,final String footIp) {
        MaterialDialog dialog = new MaterialDialog.Builder(getActivity())
                .title(R.string.nav_bottom_setting)
                .content("IP和端口已修改，是否保存？\n\n修改后，需要重新登陆用户！")
                .negativeColorRes(R.color.bg_gray)
                .negativeText(R.string.dialog_negative_text)
                .positiveColorRes(R.color.back_ground_green)
                .positiveText(R.string.dialog_positive_text)
                .onPositive(new MaterialDialog.SingleButtonCallback() {
                    @Override
                    public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                        savePreference(ip, missionPortInt, uploadPortInt,chatPortInt,filePortInt,videoPortInt,footPortInt,footIp);
                        SPUtil.remove(SPUtil.LOGIN_CODE);
                        SPUtil.remove(SPUtil.USER_NAME);
                        SPUtil.remove(SPUtil.PASS_WORD);
                        SPUtil.remove(SPUtil.PHONE_NAME);
                        OtherActivity activity = (OtherActivity) getActivity();
                        activity.setResult(OtherActivity.INDEX_CONFIG_SERVER);
                        activity.finish();
                    }
                })
                .build();
        dialog.show();
    }

    private void savePreference(String ip, int missionPortInt, int uploadPortInt,int chatPortInt,int filePortInt,int videoPortInt,int footPortInt,String footIp) {
        AppUtil.showShortToast(getContext(), "服务器设置成功");
        SPUtil.putStringValue(SPUtil.FOOTRING_SERVER_IP,footIp);
        SPUtil.putStringValue(SPUtil.SERVER_IP, ip);
        SPUtil.putIntValue(SPUtil.MISSION_PORT, missionPortInt);
        SPUtil.putIntValue(SPUtil.UPLOAD_PORT, uploadPortInt);
        SPUtil.putIntValue(SPUtil.CHAT_PORT, chatPortInt);
        SPUtil.putIntValue(SPUtil.FILE_PORT, filePortInt);
        SPUtil.putIntValue(SPUtil.VIDEO_PORT, videoPortInt);
        SPUtil.putIntValue(SPUtil.FOOT_PORT, footPortInt);
    }

    @Override
    public void onDestroyView() {
        if (mIPInputView != null) {
            mIPInputView.destroy();
        }
        if (mfootringIp != null) {
            mfootringIp.destroy();
        }
        super.onDestroyView();
    }
}
